package com.androway.model;

import java.util.ArrayList;
import java.util.List;

import android.util.Pair;

import com.androway.domains.Category;
import com.androway.domains.News;
import com.androway.domains.Service;
import com.androway.services.Requester.OnResponseListener;
import com.androway.services.Requester.RequestType;
import com.androway.utils.Query;

public class NewsModel extends AbstractModel
{
	private List<News> newsList = new ArrayList<News>();
	private List<Category> categoryList = new ArrayList<Category>();

	public NewsModel()
	{
		this.requester.setListener(new OnResponseListener()
		{
			@SuppressWarnings("unchecked")
			@Override
			public void onSuccess(RequestType type, List<?> objects, String service)
			{
				if (service.equals(Service.News))
					NewsModel.this.newsList = (List<News>) objects;
				else if (service.equals(Service.Category))
					NewsModel.this.categoryList = (List<Category>) objects;
				NewsModel.this.listener.onSuccess(type, service);
			}

			@Override
			public void onError(RequestType type, String errorMessage)
			{
				NewsModel.this.listener.onError(type, errorMessage);
			}
		});
	}

	public List<News> getNews()
	{
		return this.newsList;
	}

	public List<Category> getCategories()
	{
		return this.categoryList;
	}

	public void loadNewsFromCategory(Category category)
	{
		this.get(ApplicationModel.serverUrl + Service.News + "?category_uid=" + category.getUid(), News.class, Service.News);
	}

	public void loadCategories()
	{
		this.get(ApplicationModel.serverUrl + Service.Category, Category.class, Service.Category);
	}

	@SuppressWarnings("unchecked")
	public List<News> search(String newText)
	{
		return (List<News>) (Query.search(News.class, this.newsList, new Pair<String, String>("title", newText), new Pair<String, String>("content", newText)));
	}
}
